import { classRegistry, DrawContext, FabricImage, FabricObject } from "fabric";

import Taro from "@tarojs/taro";
import { Circle as fabricCircle, Path as fabricPath, Polygon as fabricPolygon, Rect as fabricRact } from 'fabric';
import get from "lodash/get";
import brContorls from "./brContorls";
import { invertTransform } from "./planeChange";
import tlContorls from "./tlContorls";
import utils from "src/utils/utils";
import FabricCanvas from "./FabricCanvas";

// 图片对象
export default class FabricImg extends FabricImage {

    constructor(element, options) {
        super(element, options);
        try {
            // // 这个 fileName 的内容一版是  1024_640_500_abc;
            const fileName = utils.parseUrl(element.src).name;
            const [width, height] = fileName.split("_");
            this.originWidth = Number(width) || 0;
            this.originHeight = Number(height) || 0;

        } catch (error) {
        }

        this.setControlsVisibility({
            bl: false,
            br: true,
            tl: true,
            tr: false,
            mtr: false,
            mb: false,
            ml: false,
            mr: false,
            mt: false,
        });
        this.id = utils.uuid();
        this.controls.br = brContorls;
        this.controls.tl = tlContorls;
        // this.controls.tr = trContorls;
        this.id = get(options, ["id"], Date.now());
        this.originX = "center";
        this.originY = "center";
        // 这个元素支持替换
        this.canReplace = options?.canReplace || false;
    }

    // 这个元素支持替换
    canReplace = false;
    // 图片的原始宽高
    originWidth = 100;
    originHeight = 100;

    id = 0;
    cornerSize = 120;
    touchCornerSize = 120;
    borderColor = "#fd7901";
    // objectCaching = false;
    noScaleCache = true;
    clipSvgUrl: string = "";

    lockScalingFlip = true; // 限制翻转缩放

    isH5 = false;

    _set(key: string, value: any) {
        if (key === "clipPath" && value) {
            // 初始化遮罩
            if (value) {
                if (["path", "Path"].includes(value.type)) {
                    this.clipPath = new fabricPath("").set(value);
                } else if (["polygon", "Polygon"].includes(value.type)) {
                    this.clipPath = new fabricPolygon().set(value);
                } else if (["circle", "Circle"].includes(value.type)) {
                    this.clipPath = new fabricCircle().set(value);
                } else if (["rect", "Rect"].includes(value.type)) {
                    this.clipPath = new fabricRact().set(value);
                }
                if (this.clipPath) {
                    this.clipPath.set({
                        originX: 'center',
                        originY: 'center',
                    });
                }
                // console.log("clipPath", value);
                // console.log("_clipPath", this.clipPath);
            }
        } else if (key === "type") {

        } else {
            super._set(key, value);
        }
        return this;
    }

    // _createCacheCanvas() {
    //     if (this.canvas) {
    //         this._cacheCanvas = Taro.createOffscreenCanvas({
    //             type: '2d',
    //             width: 1024,
    //             height: 1024,
    //         }) as unknown as HTMLCanvasElement;
    //         this._cacheContext = this._cacheCanvas.getContext('2d');
    //         this._updateCacheCanvas();
    //         // if canvas gets created, is empty, so dirty.
    //         this.dirty = true;
    //     }
    // }

    // 图片遮罩
    createClipPathLayer(
        this: any,
        clipPath: FabricObject,
        context: DrawContext,
    ) {
        // console.log("clipPath", clipPath);

        // taro 获取分辨率
        const canvas = Taro.createOffscreenCanvas({
            type: '2d',
            width: context.width,
            height: context.height,
        }) as unknown as HTMLCanvasElement;

        const ctx = canvas.getContext('2d')!;
        ctx.translate(context.cacheTranslationX, context.cacheTranslationY);
        ctx.scale(context.zoomX, context.zoomY);
        clipPath._cacheCanvas = canvas;
        context.parentClipPaths.forEach((prevClipPath) => {
            prevClipPath.transform(ctx);
        });
        context.parentClipPaths.push(clipPath);
        if (clipPath.absolutePositioned) {
            const m = invertTransform(this.calcTransformMatrix());

            ctx.transform(m[0], m[1], m[2], m[3], m[4], m[5]);
        }
        clipPath.transform(ctx);
        clipPath.drawObject(ctx, true, context);
        return canvas;
    }

    //@ts-ignore
    toObject(propertiesToInclude: any[] = []) {
        const data = super.toObject(
            propertiesToInclude.concat([
                'id',
                'name',
                'repeat',
                'repeatSpaceX',
                'repeatSpaceY',
                'lockMovementX',
                'lockMovementY',
                'lockRotation',
                'lockScalingX',
                'lockScalingY',
                'lockSkewingX',
                'lockSkewingY',
                'clipPath',
                'clipSvgUrl',
                'canReplace',
            ]),
        );
        data.src = this.src;
        data.crossOrigin = 'anonymous';
        return data;
    }

    // 图片是否模糊
    async isBlur() {
        // 没获取到图片宽高,就不判断是否模糊
        if (this.originWidth === 0 || this.originHeight === 0) {
            return false;
        }

        const { sideLength } = await (this.canvas as any).get_print_area(); // 单位是mm

        // 宽高同时超过预计的 毫米尺寸范围就算模糊  5.9059 是 150dpi 下的 1mm 尺寸
        if (
            this.getScaledWidth() / 1024 * sideLength > this.originWidth / (5.9059 / 2) &&
            this.getScaledHeight() / 1024 * sideLength > this.originHeight / (5.9059 / 2)
        ) {
            return true;
        }

        return false;
    }


}

// 覆盖全局注册
classRegistry.setClass(FabricImg, 'Image');
